package com.aios.action.settings.switches;

import com.aios.service.ExistValidationEnum;

public class SwitchesSaveAction extends AbstractSwitchesAction {

	private static final long serialVersionUID = 1L;

	public String execute() {
		
		validateSwitch();
		if (hasErrors()) {
			return INPUT;
		}

		if (getMode() == Mode.ADD) {

			try {
				ExistValidationEnum existValidationEnum = switchService
						.nameExistValidation(switches.getId(), switches
								.getName(), getSessionUserVariable().getId());

				if (existValidationEnum != ExistValidationEnum.NOT_EXIST) {
					actionError = getText("error.name.exist");
					return INPUT;
				}
				switchService.save(switches, getSessionUserVariable().getId());
				actionMessage = getText("success.insert");

			} catch (Exception e) {
				e.printStackTrace();
				actionError = getText("error.insert");
				return INPUT;
			}
		} else if (getMode() == Mode.EDIT) {

			try {
				ExistValidationEnum existValidationEnum = switchService
						.nameExistValidation(switches.getId(), switches
								.getName(), getSessionUserVariable().getId());

				if (existValidationEnum != ExistValidationEnum.NOT_EXIST) {
					actionError = getText("error.name.exist");
					return INPUT;
				}
				switchService.update(switches, getSessionUserVariable().getId());
				actionMessage = getText("success.update");

			} catch (Exception e) {
				e.printStackTrace();
				actionError = getText("error.update");
				return INPUT;
			}
		} else {
			actionError = getText("error.switch.notfound");
			return INPUT;
		}
		
		return SUCCESS;
	}

	private void validateSwitch() {
		if (switches.getName().isEmpty()) {
			addFieldError("switch.name", getText("error.name.empty"));
		}

	}

}
